package impl

import (
	"fmt"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/common"
	utils2 "git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/common/utils"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/dto"
	contract3 "git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/repository/common/contract"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/service/bigdata/contract"
	"git.myscrm.cn/golang/stark/v4"
	aliyunoss "github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/gin-gonic/gin"
	"io/ioutil"
)

type OpptyService struct {
	srCommonRepo contract3.SrCommonRepoIface
}

func NewOpptyService(
	srCommonRepo contract3.SrCommonRepoIface,
) contract.OpptyServiceIface {
	return &OpptyService{
		srCommonRepo: srCommonRepo,
	}
}

// GetBidDetailContent 招标详情内容
func (s *OpptyService) GetBidDetailContent(ctx *gin.Context, request *dto.GetBidDetailContentRequest) (string, error) {
	content := ""
	if request.Id == "" {
		return content, nil
	}
	querySql := fmt.Sprintf("select a.*,b.content_id,b.publish_time,b.website_name,b.data_source_code from dim_ycg_announcement_trading_center a left join dw_ycg_kfs_purchase_demand b on a.uid=b.uid where b.id = '%s' limit 1;", common.EscapeStr(request.Id))
	list, err := s.srCommonRepo.GetList(ctx.Request.Context(), querySql)
	if err != nil {
		return content, err
	}

	if len(list) > 0 {
		for _, item := range list {
			var contentId, publishTime, websiteName, dataSourceCode string
			if item["content_id"] != nil {
				contentId = item["content_id"].(string)
			}
			if item["publish_time"] != nil {
				publishTime = item["publish_time"].(string)
			}
			if item["website_name"] != nil {
				websiteName = item["website_name"].(string)
			}
			if item["data_source_code"] != nil {
				dataSourceCode = item["data_source_code"].(string)
			}
			if dataSourceCode == "trading_center" || dataSourceCode == "website_bid" {
				filePath := s.GetBidContentPath(publishTime, websiteName, contentId)
				contentHtml, err := s.GetBidOssFile(filePath)
				if err != nil {
					stark.Logger.Errorf(ctx, "get oss bid_content,err:%s", err.Error())
					content = s.getBidContentJoin(ctx, item)
				}
				if contentHtml == "" {
					content = s.getBidContentJoin(ctx, item)
				} else {
					content = contentHtml
				}
			} else {
				content = s.getBidContentJoin(ctx, item)
			}

		}
	}

	return content, nil
}

func (s *OpptyService) GetBidContentPath(publishTime string, websiteName string, id string) string {
	if publishTime == "" {
		return ""
	}
	if len(publishTime) >= 10 {
		publishTime = publishTime[0:10]
	}
	if websiteName == "" {
		websiteName = "other"
	}
	return "pub_bid/" + publishTime + "/" + websiteName + "/" + id + ".txt"
}

func (s *OpptyService) GetBidOssFile(ossFilePath string) (string, error) {
	//endpoint := "https://oss-cn-hangzhou.aliyuncs.com"
	//accessKeyId := "LTAI5tAkWjrrenAugNcuuWTA"
	//accessKeySecret := "4k7QKFjVqps3etGorMUl8LxczA0K0P"
	//bucketName := "gfyx-saas-bid-content"
	endpoint := stark.Configer.(stark.ApolloConfigerIface).GetStringValue("BidOssSetting.EndPoint", "")
	accessKeyId := stark.Configer.(stark.ApolloConfigerIface).GetStringValue("BidOssSetting.AccessKeyId", "")
	accessKeySecret := stark.Configer.(stark.ApolloConfigerIface).GetStringValue("BidOssSetting.AccessKeySecret", "")
	bucketName := stark.Configer.(stark.ApolloConfigerIface).GetStringValue("BidOssSetting.BucketName", "")
	client, err := aliyunoss.New(endpoint, accessKeyId, accessKeySecret)
	if err != nil {
		return "", err
	}
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return "", err
	}

	object, err := bucket.GetObject(ossFilePath)
	if err != nil {
		return "", err
	}

	content, err := ioutil.ReadAll(object)
	if err != nil {
		return "", err
	}
	return string(content), nil
}

func (s *OpptyService) getBidContentJoin(ctx *gin.Context, data map[string]interface{}) string {
	var projectNumber, projectName, address, developerName, owerAddress, owerPhone, owerContact, agentUnit, agentPhone, agentContact, agentAddress,
		buildScale, businessType, constructionTimeLimit, qualification, fundSource, budget string
	if data["project_number"] != nil {
		projectNumber = data["project_number"].(string)
	}
	if data["project_name"] != nil {
		projectName = data["project_name"].(string)
	}
	if data["address"] != nil {
		address = data["address"].(string)
	}
	if data["developer_name"] != nil {
		developerName = data["developer_name"].(string)
	}
	if data["ower_address"] != nil {
		owerAddress = data["ower_address"].(string)
	}
	if data["ower_phone"] != nil {
		owerPhone = data["ower_phone"].(string)
	}
	if data["ower_contact"] != nil {
		owerContact = data["ower_contact"].(string)
	}
	if data["agent_unit"] != nil {
		agentUnit = data["agent_unit"].(string)
	}
	if data["agent_phone"] != nil {
		agentPhone = data["agent_phone"].(string)
	}
	if data["agent_contact"] != nil {
		agentContact = data["agent_contact"].(string)
	}
	if data["agent_address"] != nil {
		agentAddress = data["agent_address"].(string)
	}
	if data["build_scale"] != nil {
		buildScale = data["build_scale"].(string)
	}
	if data["business_type"] != nil {
		businessType = data["business_type"].(string)
	}
	if data["construction_time_limit"] != nil {
		constructionTimeLimit = data["construction_time_limit"].(string)
	}
	if data["qualification"] != nil {
		qualification = data["qualification"].(string)
	}
	if data["fund_source"] != nil {
		fundSource = data["fund_source"].(string)
	}
	if data["budget"] != nil {
		budget = data["budget"].(string)
	}

	html := ""
	html += "<p>项目编号：" + projectNumber + "</p>"
	html += "<p>项目名称：" + projectName + "</p>"
	html += "<p>项目所在地：" + address + "</p>"
	html += "<p>招标单位：" + developerName + "</p>"
	html += "<p>招标单位地址：" + owerAddress + "</p>"
	html += "<p>招标单位联系电话：" + utils2.GetMobileEncrypt(owerPhone) + "</p>"
	html += "<p>招标单位联系人：" + utils2.GetContactNameEncrypt(owerContact) + "</p>"
	html += "<p>代理机构：" + agentUnit + "</p>"
	html += "<p>代理机构联系电话：" + utils2.GetMobileEncrypt(agentPhone) + "</p>"
	html += "<p>代理机构联系人：" + utils2.GetContactNameEncrypt(agentContact) + "</p>"
	html += "<p>代理机构地址：" + agentAddress + "</p>"
	html += "<p>建设规模：" + buildScale + "</p>"
	html += "<p>业务类型：" + businessType + "</p>"
	html += "<p>工期：" + constructionTimeLimit + "</p>"
	html += "<p>资格要求：" + qualification + "</p>"
	html += "<p>资金来源：" + fundSource + "</p>"
	html += "<p>项目预算（投标最高限价）：" + budget + "</p>"
	return html
}
